package workerwithdb.dao;

import java.util.ArrayList;
import java.util.Date;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import api.entitites.IGarage;
import api.entitites.IOrder;
import entities.Garage;

public class HibernateDAOGarage extends GenericDAOHibernate<IGarage> {
	
	private final String ID_GARAGE = "id";
	private final String FULLNESS = "fullness";
	private final String NUMBER = "number";
	private final String DEADLINE_DATE = "deadlinedate";
	private final String ORDER_STATUS = "orderstatus";
	
	public HibernateDAOGarage(){
		super(IGarage.class);
	}
	
	
	
	public void insertAllGarages(ArrayList<IGarage> garagesList,Session session){
		for(IGarage g: garagesList){
			super.saveOrUpdate(g, session);
		}

		
	}
	
	public void update(IGarage garage,Session session){
		super.update(garage,session);
	}
	
	
	public IGarage readGarage(Integer numberGarage,Session session){
		return (IGarage) super.get(NUMBER, numberGarage,session);
	}
	
	public Long getEmptyGarage(Session session){
		Criteria criteria = session.createCriteria(Garage.class).setProjection(Projections.count(ID_GARAGE)).add(Restrictions.eq(FULLNESS,false));
		Long emptyPlaces = (Long) criteria.uniqueResult();
		return emptyPlaces;		
		
	}
	
	public Long getEmptyGaragesOnDate(Date date,Session session){
		Criteria criteriaOrders = session.createCriteria(IOrder.class).setProjection(Projections.count(NUMBER)).add(Restrictions.lt(DEADLINE_DATE, date)).add(Restrictions.isNull(ORDER_STATUS));
		Long countOrders = (Long) criteriaOrders.uniqueResult();				
		Criteria criteriaGarages = session.createCriteria(Garage.class).setProjection(Projections.count(NUMBER)).add(Restrictions.eq(FULLNESS, false));
		Long countGarages = (Long) criteriaGarages.uniqueResult();	
		Long countGarage = countGarages + countOrders;
		return countGarage;					
	}
	
	
}
